package com.wt.admin.service.sys.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wt.admin.config.ConstVar;
import com.wt.admin.config.cache.Cache;
import com.wt.admin.domain.dto.sys.SysLogFindDTO;
import com.wt.admin.domain.entity.sys.SysOperationLogEntity;
import com.wt.admin.domain.entity.sys.SysSettingEntity;
import com.wt.admin.mapper.sys.SysOperationLogMapper;
import com.wt.admin.service.sys.SysOperationLogService;
import com.wt.admin.util.PageUtil;
import jakarta.annotation.Resource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class SysOperationLogServiceImpl  extends ServiceImpl<SysOperationLogMapper, SysOperationLogEntity> implements SysOperationLogService {

    @Resource
    private SysOperationLogMapper sysOperationLogMapper;
    @Resource
    private Cache<String, SysSettingEntity> settingCache;

    @Override
    public PageUtil.PageVO<SysOperationLogEntity> find(PageUtil.PageDTO<SysLogFindDTO> data) {
        return PageUtil.findPage(data, (page) -> sysOperationLogMapper.find(page,data.getData()));
    }

    @Transactional
    @Override
    public void add(List<SysOperationLogEntity> logQueue) {
        saveBatch(logQueue);
    }

    @Async("newAsync")
    @Override
    public void clear() {
        log.debug("操作日志清理-开始");
        SysSettingEntity setting = settingCache.get(ConstVar.SettingModel.SETTING);
        if(ObjectUtil.isEmpty(setting) || ObjectUtil.isEmpty(setting.getApplication())){
            return;
        }
        String string = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, -setting.getApplication().getOperationLogStored())
                .toString(DatePattern.NORM_DATETIME_PATTERN);
        sysOperationLogMapper.clearByTime(string);
        log.debug("操作日志清理-结束");
    }

}
